package com.poly.common.core.validate;



import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

/**
 * ValidatorUtils 校验工具类
 */
public class ValidatorUtils {
    private static Validator validator;

    static {
        validator = Validation.buildDefaultValidatorFactory().getValidator();
    }
    /**
     *
     * @param t
     * @param groups
     * @param <T>
     * @return
     */
    public static <T> void validateEntity(T t, Class<?>... groups){
        Set<ConstraintViolation<T>> set = validator.validate(t,groups);
        if (!set.isEmpty()) {
            ConstraintViolation<T> constraint = (ConstraintViolation<T>)set.iterator().next();
            throw new IllegalArgumentException(constraint.getMessage());
        }
    }

}
